package com.pjmike.netty.conf;

import com.pjmike.netty.server.http.web.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class RestControllerRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
    private Environment environment;
    private static final String SCAN_URL ="netty.httpserver.scanpackage";
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {

    }

    /**
     * 先执行postProcessBeanDefinitionRegistry方法
     * 在执行postProcessBeanFactory方法
     */
     @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
         BindResult<String> ScanUrlBindResult = Binder.get(environment).bind(SCAN_URL, String.class);
         String bindResult= ScanUrlBindResult.get();
         //扫描自定义注解
        ClassPathBeanDefinitionScanner scanner = new
                ClassPathBeanDefinitionScanner(registry);
        // bean 的名字生成规则在AnnotationBeanNameGenerator
        scanner.setBeanNameGenerator((beanDefinition, beanDefinitionRegistry) -> beanDefinition.getBeanClassName());
        scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
        scanner.scan(bindResult);
    }
    @Override
    public void setEnvironment(final Environment environment) {
        this.environment = environment;
    }

}